<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="设备计划单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="code"
            >
              <a-input v-model="model.code" disabled placeholder=""></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowType">
              <j-dict-select-tag
                type="list"
                v-model="model.flowType"
                dictCode="material_application_flow_type"
                placeholder="请选择审批流程"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <!--<a-col :span="8">
            <a-form-model-item
              label="制单人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createBy"
            >
              <a-input v-model="model.createBy" placeholder="请输入申请人" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="sysOrgCode"
            >
              <j-select-depart disabled v-model="model.sysOrgCode" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createTime"
            >
              <a-input v-model="model.createTime" disabled></a-input>
            </a-form-model-item>
          </a-col>-->
          <a-col :span="12">
            <a-form-model-item
              label="开始日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="startTime"
            >
              <j-date
                placeholder="请选择开始日期"
                v-model="model.startTime"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="结束日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="endTime"
            >
              <j-date
                placeholder="请选择结束日期"
                v-model="model.endTime"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-input v-model="model.sourceFrom" type="hidden" />
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="计划明细" :key="refKeys[0]" :forceRender="true">
<!--        <div class="table-operator">-->
<!--          &lt;!&ndash; 暂时不允许添加后期需要再打开 &ndash;&gt;-->
<!--          &lt;!&ndash; <a-button @click="addMateriel" type="primary" icon="plus" :disabled="formDisabled">新增</a-button> &ndash;&gt;-->
<!--          <a-button @click="copyRow" type="primary" icon="copy" :disabled="formDisabled">复制</a-button>-->
<!--        </div>-->
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussMaterialProcurementPlanDetailTable.loading"
          :columns="bussMaterialProcurementPlanDetailTable.columns"
          :dataSource="bussMaterialProcurementPlanDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="false"
          :toolbar="true"
          rowSelectionType="radio"
          :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['clearSelection'] }"
          class="bold-border"
          :clickSelectRow="true"

        >
          <template v-slot:toolbarSuffix>
            <a-button
              type="primary"
              icon="PlusCircleOutlined"
              @click="addMateriel"
              :disabled="formDisabled"
            >新增</a-button>
          </template>
          <template v-slot:action="props">
            <a-popconfirm
              v-show="!formDisabled"
              title="确定删除吗？"
              @confirm="handleDelDetail(props)"
            >
              <a>删除</a>
            </a-popconfirm>
          </template>
          <!--<template v-slot:supplierId="props">
            <tsl-mat-supplier
              v-model="props.value"
              :isDisabled="formDisabled"
              :rowData="props"
              @handlerOk="supplierOk"
            ></tsl-mat-supplier>
          </template>-->
<!--          <template v-slot:supplierId="props">
            <tsl-purchase-supplier
              v-model="props.value"
              :isDisabled="formDisabled"
              :rowData="props"
              @handlerOk="supplierOk"
            ></tsl-purchase-supplier>
          </template>-->
          <template v-slot:supplierId="props">
            <a-input v-model="props.value" placeholder="请选择供应商" @click="chooseSupplier()" :disabled="formDisabled"> </a-input>
            <tsl-purchase-supplier ref="selectSuppliersList" :rowData="props" :isDisabled="formDisabled" @handleOk="supplierOk"  checkval="radio"></tsl-purchase-supplier>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>

    <erp-goods-list-model ref="selectGoodsList" category="6" @goodsOk="goodsOk" checkval="radio"></erp-goods-list-model>
  </a-spin>
</template>

<script>
import { getAction, postAction, putAction, httpAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import ErpGoodsSupplierListModal from '@comp/base/modal/ErpGoodsSupplierListModal'
import BussApplicationListModal from '@comp/base/modal/BussApplicationListModal'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import store from '@/store'
import moment from 'dayjs'
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
/*import TslMatSupplier from '@comp/tsl/cell/TslMatSupplier.vue'*/
import TslPurchaseSupplier from '@comp/tsl/cell/TslPurchaseSupplier.vue'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

export default {
  name: 'BussEquipmentProcurementPlanForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    BussApplicationListModal,
    JSelectDepart,
    ErpGoodsListModel,
    /*TslMatSupplier,*/
    TslPurchaseSupplier,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  data() {
    return {
      categoryOptions: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      category: '1',
      /*applicationId: '1',*/
      row: {},
      model: {
        code: '',
        flowType: 1,
        sourceFrom: '13'
        /*applicationId: '',*/
        /*submissionDate: '',*/
      },
      curRow: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        /*startTime: [{ required: true, message: '请选择开始日期!' }],
        endTime: [{ required: true, message: '请选择结束日期!' }],*/
      },
      refKeys: ['bussMaterialProcurementPlanDetail'],
      tableKeys: ['bussMaterialProcurementPlanDetail'],
      activeKey: 'bussMaterialProcurementPlanDetail',
      // 原料采购计划单明细
      bussMaterialProcurementPlanDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          /*{
            title: '行号',
            key: 'seq',
            // type: JVXETypes.input,
            width: '50px',
            defaultValue: '',
          },*/
          {
            title: '原料请购单号',
            key: 'applicationCode',
            width: '200px',
            placeholder: '',
            defaultValue: '',
          },
          {
            title: '物料编码',
            key: 'materialCode',
            width: '150px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true,
                message: '',
              },
            ],
          },
          {
            title: '物料名称',
            key: 'materialName',
            width: '200px',
            placeholder: '',
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'spec',
            width: '120px',
            placeholder: '',
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'unit',
            width: '80px',
          },
          {
            title: '请购数量',
            key: 'applyNum',
            width: '150px',
            type: JVXETypes.normal,
          },
          {
            title: '现有库存',
            key: 'existInventory',
            width: '150px',
          },
          {
            title: '允许最小库存',
            key: 'minimumInventory',
            width: '150px',
          },
          {
            title: '允许最大库存',
            key: 'maxInventory',
            width: '150px',
          },
          /*{
            title: '库存可用数量',
            key: 'availInvNum',
            width: '150px',
            type: JVXETypes.inputNumber,
          },*/
          {
            title: '采购数量',
            key: 'num',
            type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true,
                message: '请输入${title}',
              },
            ],
          },
          {
            title: '供货单位',
            key: 'supplierName',
            type: JVXETypes.slot,
            width: '220px',
            placeholder: '请选择${title}',
            slotName: 'supplierId',
            validateRules: [
              {
                required: true,
                message: '请选择${title}'
              }
            ]
          },
          {
            title: '到货日期',
            key: 'arrivalDate',
            type: JVXETypes.date,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/plan/bussMaterialProcurementPlan/add',
        edit: '/plan/bussMaterialProcurementPlan/edit',
        queryById: '/plan/bussMaterialProcurementPlan/queryById',
        queryMaterialApplicationDetails: '/plan/bussMaterialProcurementPlan/queryMaterialApplicationDetails',
        bussMaterialProcurementPlanDetail: {
          list: '/plan/bussMaterialProcurementPlan/queryBussMaterialProcurementPlanDetailByMainId',
          applicationDetail: '/plan/bussMaterialProcurementPlan/applicationDetail',
          applicationDetailById: '/plan/bussMaterialProcurementPlan/applicationDetailById',
        },
      },
    }
  },

  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.model.sourceFrom = '13'

    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.sysOrgCode = user.departIds
    }

    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      console.log(this.model)
      //刷新子表数据
      this.editAfter()
    }
  },
  methods: {
    chooseSupplier(){
      this.$nextTick(() => {
        this.$refs.selectSuppliersList.add()
      })
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/equipment_plan_code'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
        }
      })
    },
    goodsOk(data) {
      let detail = {}
      detail.materialName = data.name
      detail.materialCode = data.code
      detail.materialId = data.id
      detail.spec = data.noneSpec
      detail.unit = data.meUnit_dictText
      this.bussMaterialProcurementPlanDetailTable.dataSource.push(detail)
    },
    addMateriel() {
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    cellClickEvent({ row, column }) {
      // if (column.property === 'supplierName') {
      //   this.row = row
      //   this.category = row.materialId
      //   console.log(this.category)
      //   this.$refs.selectSuppliersList.add()
      //   this.$refs.selectSuppliersList.title = '选择供应商'
      //   this.$refs.selectSuppliersList.disableSubmit = false
      // }
    },
    supplierOk({ row, data }) {
      this.$set(this.row, 'supplierName', data.supplierName)
      this.$set(this.row, 'supplierId', data.id)
      row.supplierId = data.id
      row.supplierName = data.supplierName
      this.$forceUpdate()
    },
    addBefore() {
      this.bussMaterialProcurementPlanDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    add() {
      this.getSequenceNum()
      //显示请购单明细
      this.bussMaterialProcurementPlanDetailTable.dataSource = []
      let materialApplications = store.getters.materialApplications
      if (materialApplications && materialApplications.length > 0) {
        this.bussMaterialProcurementPlanDetailTable.dataSource = materialApplications.map((item, index) => ({
          applicationDetailId: item.detailId,
          applicationId: item.id,
          applicationCode: item.code,
          materialId: item.materialId,
          materialCode: item.materialCode,
          materialName: item.materialName,
          spec: item.spec,
          unit: item.unit,
          applyNum: item.applyNum,
          availInvNum: item.availInvNum,
          existInventory: item.existInventory,
          minimumInventory: item.minimumInventory,
          maxInventory: item.maxInventory,
        }));
        // postAction(this.url.queryMaterialApplicationDetails, { ids: applicationIds })
        //   .then(res => {
        //     if (res.success && res.result) {
        //       // 处理返回的数据并填充到子表
        //       this.bussMaterialProcurementPlanDetailTable.dataSource = res.result.map((item, index) => ({
        //         applicationDetailId: item.id,
        //         applicationId: item.applicationId,
        //         applicationCode: item.applicationCode,
        //         materialId: item.materialId,
        //         materialCode: item.materialCode,
        //         materialName: item.materialName,
        //         spec: item.spec,
        //         unit: item.unit,
        //         applyNum: item.applyNum,
        //         availInvNum: item.availInvNum,
        //       }));
        //     }
        //   });
      }
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.editAfter()
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        //todo 暂时没有供货商关联
        this.requestSubTableData(
          this.url.bussMaterialProcurementPlanDetail.list,
          params,
          this.bussMaterialProcurementPlanDetailTable
        )
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        details: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    selectRowChange({ type, action, selectedRows, $event }) {
      this.curRow = selectedRows
    },
    copyRow() {
      if (this.curRow && this.curRow.length > 0) {
        let data = {}
        Object.assign(data, this.curRow[0])
        data.id = data.id + 'aaa'
        data.seq = this.bussMaterialProcurementPlanDetailTable.dataSource.length + 1
        this.bussMaterialProcurementPlanDetailTable.dataSource.push(data)
      } else {
        this.$message.warn('请选择一条记录复制！')
        return
      }
    },
    //提交表单数据
    request(formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true

      httpAction(url, formData, method)
        .then((res) => {
          if (res.success) {
            //241119修改提交时还要判断是否直接进入审批流
            /*if (!this.model.id) {
              this.model.dataId = res.message
              this.applySubmit(this.model)
            }*/
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          let params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          definitionStartByDataId(record.dataId, 'MaterialProcurementPlanService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
    handleDelDetail(props) {
      props.target.removeRows(props.row)
      if (this.bussMaterialProcurementPlanDetailTable.dataSource.length > 0) {
        this.bussMaterialProcurementPlanDetailTable.dataSource.splice(
          this.bussMaterialProcurementPlanDetailTable.dataSource.findIndex((d) => d.id === props.row.id),
          1
        )
      }
    },
  },
}
</script>

<style scoped></style>
